<?php
namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Models\Admin\AfterSale;
use App\Models\Admin\AdminBonusLog;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Salebonusrule;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session; 
use Carbon\Carbon;
use Auth;
use DB;

class CommonController extends Controller
{
	public $result = array("status"=>0,'msg'=>'请求成功','data'=>"");
	//更新售后订单信息
	public function updateAfterSale(Request $request)
    {
		$after_arr = AfterSale::from('after_sale as af')
					->select('af.*','au.branch_id')
					->leftjoin('admin_users as au','af.after_sale_id','=','au.id')
					->where('af.after_status','=',0)
					->get();

		foreach($after_arr as $v){
    		$data_upd = array();
    		$admin_upd = array();
    		$data_ins = array();

    		if($v->after_time==0){
    			if(($v->after_time+1) <= ($v->buy_length)){
    				$cur_time = Carbon::parse('-'.($v->after_time+1).' months')->toDateTimeString();
					if($cur_time >= $v->buy_time){
	    				//售后表更新
						$data_upd['after_time'] = $v->after_time+1;
						$bool1 = AfterSale::where("id","=",$v->id)->update($data_upd);
						//管理员表更新
	    				$adminuser = AdminUser::where('id','=',$v->after_sale_id)->first();
                        $admin_upd['bonus'] = $adminuser->bonus;
                        $data_ins['money'] = 0;
                        if((int)$v->sbr_id>0){
                            $saleRuleModel = new Salebonusrule();
                            $sbi = $saleRuleModel->getSaleRuleDetail($v->sbr_id);
                            $admin_upd['bonus'] = $admin_upd['bonus'] + (intval($v->after_money * $sbi['after_first_bonus']))/100;
                            $data_ins['money'] = (intval($v->after_money * $sbi['after_first_bonus']))/100;
                        }
	    				AdminUser::where('id','=',$v->after_sale_id)->update($admin_upd);
	    				//业绩流水表
	    				$data_ins['admin_users_id'] = $v->after_sale_id;
						$data_ins['type'] = 1;
						$data_ins['cur_bonus'] = $admin_upd['bonus'];
						$data_ins['member_name'] = $v->member_name;
						$data_ins['member_phone'] = $v->member_phone;
						$data_ins['goods_name'] = $v->goods_name;
						$data_ins['goods_money'] = $v->goods_money;
						$data_ins['order_number'] = $v->order_number;
						$data_ins['remarks'] = $v->remarks;
                        $adminBonusModel = new AdminBonusLog();
                        $adminBonusModel->adminBonusLogInsert($data_ins);
					}
    			}
    		}else if(($v->after_time+1) <= ($v->buy_length)){
    			$cur_time = Carbon::parse('-'.($v->after_time+1).' months')->toDateTimeString();
    			if($cur_time >= $v->buy_time){
                  
    				//售后表更新
    				$data_upd['after_time'] = $v->after_time+1;
    				$bool1 = AfterSale::where("id","=",$v->id)->update($data_upd);
    					
    				//管理员表更新
    				$adminuser = AdminUser::where('id','=',$v->after_sale_id)->first();
                    $one = 0;
                    if((int)$v->sbr_id>0){
                        $saleRuleModel = new Salebonusrule();
                        $sbi = $saleRuleModel->getSaleRuleDetail($v->sbr_id);
                        $one = (intval($v->after_money * $sbi['after_first_bonus']))/100;
                    }
    				$new_bonus = round(($v->after_money - $one)*100/($v->buy_length-1))/100;
    				$admin_upd['bonus'] = ($adminuser->bonus)+$new_bonus;
    				AdminUser::where('id','=',$v->after_sale_id)->update($admin_upd);
    				
    				//业绩流水表
    				$data_ins['admin_users_id'] = $v->after_sale_id;
					$data_ins['type'] = 1;
					$data_ins['money'] = $new_bonus;
					$data_ins['cur_bonus'] = $admin_upd['bonus'];
					$data_ins['member_name'] = $v->member_name;
					$data_ins['member_phone'] = $v->member_phone;
					$data_ins['goods_name'] = $v->goods_name;
					$data_ins['goods_money'] = $v->goods_money;
					$data_ins['order_number'] = $v->order_number;
					$data_ins['remarks'] = $v->remarks;
					$adminBonusModel = new AdminBonusLog();
					$adminBonusModel->adminBonusLogInsert($data_ins);
    			}
    		}else{
    			//售后表更新
    			$data_upd['after_status'] = 1;
    			AfterSale::where("id","=",$v->id)->update($data_upd);
    		}
    		
    		unset($data_upd);
    		unset($admin_upd);
    		unset($data_ins);
    	}
		
        echo '<h1>666666</h1>';die;
	}	
	
	//查询个人业绩
	public function bonus(Request $request)
    {
		if ($request->ajax()) {
            
            $sortName = $request->post("sortName");    //排序列名
			$sortOrder = $request->post("sortOrder");   //排序（desc，asc）
			$pageNumber = $request->post("pageNumber");  //当前页码
			$pageSize = $request->post("pageSize");   //一页显示的条数
			$start = ($pageNumber-1)*$pageSize;   //开始位置
			$search = $request->post("search",'');  //搜索条件
			
			$total = AdminUser::from('admin_bonus_log as abl')
					->select('au.name as admin_name','abl.*')
					->leftjoin('admin_users as au','admin_users_id','=','au.id')
					->where('au.id','=',Auth::guard('admin')->user()->id);
	        $rows = AdminUser::from('admin_bonus_log as abl')
					->select('au.name as admin_name','abl.*')
					->leftjoin('admin_users as au','admin_users_id','=','au.id')
					->where('au.id','=',Auth::guard('admin')->user()->id);
	        
	        
	        if(trim($search)){
	        	$total->where(function ($query) use ($search) {
                    $query->where('abl.member_name', 'LIKE', '%' . $search . '%')
                    ->orwhere('abl.goods_name', 'LIKE', '%' .$search . '%')
                    ->orwhere('au.name', 'LIKE', '%' .$search . '%')
                    ->orwhere('abl.order_number', 'LIKE', '%' .$search . '%')
                    ->orwhere('abl.member_phone', 'LIKE', '%' .$search . '%');
                });
	        	$rows->where(function ($query) use ($search) {
                    $query->where('abl.member_name', 'LIKE', '%' . $search . '%')
                    ->orwhere('abl.goods_name', 'LIKE', '%' .$search . '%')
                    ->orwhere('au.name', 'LIKE', '%' .$search . '%')
                    ->orwhere('abl.order_number', 'LIKE', '%' .$search . '%')
                    ->orwhere('abl.member_phone', 'LIKE', '%' .$search . '%');
                });
	        }
	        
	        $data['total'] = $total->count();
	        $data['rows'] = $rows->skip($start)->take($pageSize)
					        ->orderBy($sortName, $sortOrder)
					        ->get();
	        
	        return response()->json($data);
        }
        return view('admin.index.bonus');
	}
	
	//对比验证码
	public function getYzm(Request $request){
		if(Session::get('milkcaptcha') == $request->yzm){
        	return response()->json($this->result);
	    }else{
	    	$this->result['status'] = 1;
			$this->result['msg'] = '验证码有误！！！';
	    	return response()->json($this->result);
	    }
	}

    public function getTitle(){
        /*--- start 跨域测试用 (待删除) ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        /*--- end 跨域测试用---*/
        $returnData = ErrorCode::$admin_enum["success"];
        $returnData['data'] = \Illuminate\Support\Facades\DB::table("configs")->where('id',1)->select("title","qy_redirect","agent_url", "seo_title")->first();
        return response()->json($returnData);
    }
}	